package com.snail.controller;
import com.snail.model.pojo.BizChatMessage;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.snail.aiChat.model.ChatQuery;
import com.snail.response.BaseResponse;
import com.snail.response.ResultUtils;
import com.snail.service.BizChatMessageService;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.ChatMemoryRepository;
import org.springframework.ai.chat.messages.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.util.List;

/**
 * @author Monica
 * @date 2025/6/28 13:46
 */
@RestController
@RequestMapping("/chat")
public class ChatController {
    @Autowired
    private ChatClient chatClient;
    @Autowired
    private BizChatMessageService bizChatMessageService;
    @Autowired
    private ChatMemoryRepository chatMemoryRepository;

    @RequestMapping(value = "/fluxChat", produces = "text/event-stream")
    public Flux<ServerSentEvent<String>> fluxChat(@RequestBody ChatQuery chatQuery) {
        String message = chatQuery.getMessage();
        String chatId = chatQuery.getChatId();
        Integer userId = chatQuery.getUserId();
        String chatName = chatQuery.getChatName();
        System.out.println("用户输入：" + message);
        if (StringUtils.isEmpty(message)) {
            return Flux.error(new IllegalArgumentException("消息内容不能为空"));
        }
        if (userId != null) {
            bizChatMessageService.saveChatMessage(userId, chatId, message, chatName);
        }
        return chatClient.prompt()
                .user(message)
                .advisors(a -> a.param(ChatMemory.CONVERSATION_ID, chatId == null ? "1" : chatId))
                .stream()
                .content()
                .map(content -> ServerSentEvent.<String>builder()
                        .data(content.replace("\n", "\\n"))
                        .build());
    }


    @GetMapping("/getConversationsByUserId")
    public BaseResponse<List<BizChatMessage>> getConversationsByUserId() {
        Long userId = StpUtil.getLoginIdAsLong();

        List<BizChatMessage> conversations = bizChatMessageService.list(
                new LambdaQueryWrapper<BizChatMessage>()
                        .eq(BizChatMessage::getUserId, userId)
        );
        return ResultUtils.success(conversations);
    }

    @GetMapping("/getConversationByChatId")
    public BaseResponse<List<Message>> getConversationByChatId(@RequestParam String chatId) {
        List<Message> messages = chatMemoryRepository.findByConversationId(chatId);

        return ResultUtils.success(messages);
    }

    @DeleteMapping("/deleteConversationByChatId")
    public BaseResponse<Boolean> deleteConversationByChatId(@RequestParam String chatId) {
        // redis删除
        chatMemoryRepository.deleteByConversationId(chatId);
        // mysql删除
        Long userId = StpUtil.getLoginIdAsLong();
        bizChatMessageService.remove(new LambdaQueryWrapper<BizChatMessage>()
                .eq(BizChatMessage::getChatId, chatId)
                .eq(BizChatMessage::getUserId, userId));
        return ResultUtils.success(true);
    }

    @GetMapping("/renameSession")
    public BaseResponse<Boolean> renameSession(@RequestParam String chatId, @RequestParam String chatName) {
        Long userId = StpUtil.getLoginIdAsLong();
        BizChatMessage bizChatMessage = new BizChatMessage();
        bizChatMessage.setChatName(chatName);
        boolean update = bizChatMessageService.update(bizChatMessage,
                new LambdaQueryWrapper<BizChatMessage>()
                        .eq(BizChatMessage::getUserId, userId)
                        .eq(BizChatMessage::getChatId, chatId)
        );
        return ResultUtils.success(update);
    }
}
